<html>
<head>
<title>記憶翻牌</title>
<style>
.grid {
display: grid;
grid-template-columns: repeat(4, 100px);
grid-gap: 10px;
}
.card {
width: 100px;
height: 100px;
background-color: #111;
color: white;
display: flex;
align-items: center;
justify-content: center;
font-size: 36px;
cursor: pointer;
}
.card.flipped {
background-color: white;
color: #111;
}
.hidden {
visibility: hidden;
}
</style>
</head>
<body>
<h1>記憶翻牌</h1>
<button id='btnRenew' onclick="renew()">
重新</button>
<div class="grid" id='divMain'></div>
</body>
</html>
畫面主要是透過javascript產出,
所以只在html上放置一個畫布(div)。
const items = ['🍇', '🍋', '🥝', '🍌', '🍎', '🍓']; //設置圖案
let firstCard = null; //翻開的第一張
let secondCard = null; //翻開的第二張
let locked = false;
function ini() {
const randomCards = setCard(items); //洗牌
const board = document.getElementById('divMain');
board.innerHTML = "";
randomCards.forEach(item => {
const card = document.createElement('div');
card.classList.add('card');
card.dataset.icon = item;
card.addEventListener('click', flipCard);
board.appendChild(card);
}); //設置每張卡牌(卡面&觸發)
}
//翻牌
function flipCard() {
if (locked || this === firstCard)
return;
this.classList.add('flipped');
this.textContent = this.dataset.icon;
if (!firstCard)
{
firstCard = this;
return;
}
else{
secondCard = this;
checkAnswer(); //檢查
}
}
//確認是否一樣
function checkAnswer() {
if (firstCard.dataset.icon === secondCard.dataset.icon){
//一樣就移除
firstCard.removeEventListener('click', flipCard);
secondCard.removeEventListener('click', flipCard);
resetBoard();
}
else {
//不一樣就復原
locked = true;
setTimeout(() => {
firstCard.classList.remove('flipped');
secondCard.classList.remove('flipped');
firstCard.textContent = '';
secondCard.textContent = '';
resetBoard();
}, 1000);
}
}
//更新
function resetBoard() {
firstCard = null;
secondCard = null;
locked = false;
}
//洗牌
function setCard(cards) {
let copy = [...cards, ...cards];
copy.sort(() => Math.random() - 0.5);
return copy;
}
window.onload = ini;
//重新按鈕
function renew() {
ini();
}
小記:
原先在//洗牌的地方是這樣寫↓
function setCard(cards) {
let copy = cards;
let result = copy.push(cards);
result.sort(() => Math.random() - 0.5);
return result;
}
後來發現result 只是得到了copy的長度。
又將排序的result改成copy,
但這樣的copy只是多長了一個舊cards的值。